package com.umbacos.udm.client.arch;

import com.google.gwt.core.client.Duration;
import com.google.gwt.user.client.ui.Widget;

public class ResizeAnimation implements Animation{
	
	protected final Widget widget;
    protected final int targetWidth;
    protected final int targetHeight;
    protected final int duration;
    private Duration startTime;
    private int initialWidth;
    private int initialHeight;
    
    public ResizeAnimation(Widget widget, int duration, int targetWidth, int targetHeight) {
        this.widget = widget;
        this.targetWidth = targetWidth;
        this.targetHeight = targetHeight;
        this.duration = duration;
    }

	public void afterLastFrame() {
		// NOP
	}

	public boolean animateOneFrame() {

		final int elapsed = startTime.elapsedMillis();
		if (elapsed == 0)
			return Animator.NOT_FINISHED;

		float fraction = (float) elapsed / (float) duration;
		if ((fraction >= 1.0f) ||(isFinished()==Animator.FINISHED)) {
			widget.setSize(targetWidth + "px", targetHeight + "px");
			return Animator.FINISHED;
		} else {
			int x = Math.round(initialWidth + ((targetWidth - initialWidth) * fraction));
			int y = Math.round(initialHeight + ((targetHeight - initialHeight) * fraction));
			widget.setSize(x + "px", y + "px");
			return Animator.NOT_FINISHED;
		}
	}

	private boolean isFinished(){
    	int norma=(widget.getOffsetWidth() - targetWidth);
    	norma = norma*norma;
		if (norma<2) return Animator.FINISHED;
		else return Animator.NOT_FINISHED;
	}
	
	public boolean beforeFirstFrame() {
        startTime = new Duration();
        initialWidth = widget.getOffsetWidth();
        initialHeight = widget.getOffsetHeight();
        return isFinished();
	}

	public Widget getWidget() {
		return widget;
	}

}
